/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.buzzwords.resources;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.buzzwords.dataacess.Database;
import com.buzzwords.factories.BuzzwordDatabaseFactory;
import com.buzzwords.factories.DatabaseFactory;
import com.buzzwords.model.Buzzword;
import com.buzzwords.model.Definition;
import com.buzzwords.model.Locale;
import com.buzzwords.model.Rating;
import com.buzzwords.model.User;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONObject;

/**
 *
 * @author devinpartlow
 */
@Path("/rating/")
public class RatingResource {

    @Path("/post/")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public String postRating(String json) {
        JSONObject JSONRating = JSONObject.fromObject(json);

        DatabaseFactory databaseFactory = new BuzzwordDatabaseFactory();
        Database userDatabase = databaseFactory.getDatabase(BuzzwordDatabaseFactory.USER_UDID);
        Database buzzwordDatabase = databaseFactory.getDatabase(BuzzwordDatabaseFactory.BUZZWORD_KEY);
        Database definitionDatabase = databaseFactory.getDatabase(BuzzwordDatabaseFactory.DEFINITION_KEY);

        // create user
        String udid = JSONRating.getString("udid");
        User user = new User(udid);
        List<Object> dbUsers = userDatabase.performRead(user.getUDID(), new ArrayList());
        if(!dbUsers.isEmpty() && dbUsers.size() == 1) {
            user = (User)dbUsers.get(0);
        } else {
            user.setUsername("iPhone " +udid.substring(30));
        }

        // create rating
        Rating rating = new Rating();
        rating.setUsername(user.getUsername());
        rating.setLike(JSONRating.getBoolean("like"));
        rating.setComment(JSONRating.getString("comments"));

        // get definition
        Key definitionKey = KeyFactory.stringToKey(JSONRating.getString("buzzwordKey"));
        List<Object> definitions = definitionDatabase.performRead(definitionKey, new ArrayList());
        Definition definition = (Definition)definitions.get(0);

        // add rating to definition
        definition.getRatings().add(rating);

        // persist
        definitionDatabase.performCreate(definition);

        return "Rating stored";
    }

}
